/*
 * Copyright 2002-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.ws.samples.mtom.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.activation.DataHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/** @author Arjen Poutsma */
@Service
class ContentRepositoryImpl implements ContentRepository {

	private static final Logger logger = LoggerFactory.getLogger(ContentRepositoryImpl.class);

	@Value(value = "#{ systemProperties['java.io.tmpdir'] }") //
	private String fileStorePath;

	@Override
	public File loadContent(String name) {
		return new File(this.fileStorePath, name + ".tmp");
	}

	@Override
	public void storeContent(String name, DataHandler content) throws IOException {

		File outFile = new File(this.fileStorePath, name + ".tmp");
		logger.info("Storing content in file: {}", outFile.getAbsolutePath());

		int i = 0;
		byte[] buffer = new byte[1024];
		try (InputStream in = content.getInputStream()) {
			try (OutputStream out = new FileOutputStream(outFile)) {
				while ((i = in.read(buffer, 0, buffer.length)) > 0) {
					out.write(buffer, 0, i);
				}
			}
		}
		logger.info("Content stored.");
	}
}
